package com.bestcem.xm.user.service.impl.third;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.exception.BusinessException;
import com.bestcem.xm.user.service.third.ApiHelperService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 第三方接口
 *
 * @author panyun <yun.pan@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/3 14:22
 */
@Service
@Slf4j
public class ApiHelperServiceImpl implements ApiHelperService {

    @Resource
    private RestTemplate restTemplate;

    @Value("${url.wjlink_long_to_short_url}")
    private String longToShortUrl;

    /**
     * 调用第三方接口生成短链接
     *
     * @param url
     * @return com.bestcem.xm.util.ServiceResult<java.lang.String>
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/3 14:23
     */
    @Override
    public ServiceResult<String> aioConvertShortUrl(String url, String customDomainUrl) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("url", url);
        JSONObject response = wjlinkShortUrl(paramMap);
        if (response == null || response.getInteger("code") != 0) {
            throw new BusinessException("短链接服务获取出错");
        }
        log.info("Now the shorten response = {}", response.toJSONString());
        if (StringUtils.isEmpty(customDomainUrl)) {
            return ServiceResult.success(response.getString("short_url"));
        }
        return ServiceResult.success(customDomainUrl + "/t/" + response.getString("tcode"));
    }

    private JSONObject wjlinkShortUrl(Map<String, String> paramMap) {
        //RetrofitClient 构建x-www-form-urlencoded，一直有问题，换个原生写法
        try (HttpResponse response = HttpRequest.post(longToShortUrl)
            .body(JSON.toJSONString(paramMap))
            .execute()) {

            if (response.isOk()) {
                return JSONObject.parseObject(response.body());
            } else {
                return null;
            }
        }
    }
}
